/**
 * Created by root on 2015/1/13.
 */
var doPage = function(page, limit){
    $.post('/admin/store', {
        page: page,
        limit: limit
    }, function(res){
        var result = res.result;
        var count = res.count;
        var pageCount = res.pageCount;
        var currentPage = res.currentPage;
        var limit = res.limit;

        var oPageUl = $('#js-page');
        var oStart = $('#js-start')
        var oEnd = $('#js-end');
        var oTotal = $('#js-total');
        var oUserBody = $('#js-user-body');

        oStart.text((currentPage - 1) * limit + 1);
        oEnd.text((currentPage * limit) > count ? count : (currentPage * limit));
        oTotal.text(count);

        var html = '';
        for(var i= 0,len=result.length; i < len;i++){
            var data = result[i];
            html += '<tr>';
            //html += '<td><p class="text-left tb-text"><input type="text" data-sid="' + data._id + '" data-origin="' + data.text + '"  name="text" value="' + data.text + '"/></p></td>';
            html +=	'<td><p class="text-center tb-text"><a href="/admin/question?sid=' + data._id + '" class="links">' + data.text + '</a></p></td>';
            html += '<td><p class="text-left tb-text">' + ((data.category && data.category.text) || '') + '</p></td>';
            html += '<td><p class="text-left tb-text"><input type="text" data-sid="' + data._id + '" data-origin="' + data.profession + '"  name="profession" value="' + (data.profession || '') + '"/></p></td>';
            //html +=	'<td><p class="text-center tb-text">' + (data.profession || '')  + '</p></td>';

            html += '<td><p class="text-left tb-text"><input type="text" data-sid="' + data._id + '" data-origin="' + data.drill + '"  name="drill" value="' + data.drill + '"/></p></td>';
            //html +=	'<td><p class="text-center tb-text">' + data.drill + '</p></td>';

            html += '<td><p class="text-left tb-text"><input type="text" data-sid="' + data._id + '" data-origin="' + data.score + '"  name="score" value="' + data.score + '"/></p></td>';
            //html +=	'<td><p class="text-center tb-text">' + data.score + '</p></td>';

            html += '<td><p class="text-left tb-text"><input type="text" class="" data-sid="' + data._id + '" data-origin="' + data.duration + '"  name="duration" value="' + data.duration + '"/></p></td>';
            //html +=	'<td><p class="text-center tb-text">' + data.duration + '</p></td>';

            html +=	'<td><p class="text-center tb-text">' + data.bounty + '</p></td>';
            html +=	'<td><p class="text-center tb-text">' + data.bestScore + '</p></td>';
            html +=	'<td><p class="text-center tb-text">' + ((data.bestUser && data.bestUser.name) || '无') + '</p></td>';
            html += '<td><p class="text-center tb-text delbtn" data-sid="' + data._id + '"><a class="btn mini"><i class="icon-trash"></i> 删除</a></p></td>';
            html += '</tr>';
        }
        oUserBody.html(html);

        var page = '';
        if(currentPage > 1){
            page += '<li class="prev"><a data-page="' + (currentPage - 1) + '">← 上一页</a></li>';
            if(currentPage > 4){
                page += '<li><a data-page="1">' + 1 + '</a></li>';
            }
            if(currentPage > 5){
                page += '<li class="disabled"><a> ... </a></li>';
            }
        }

        for(var i=3; i > 0; i--){
            if((currentPage - i) > 0){
                page += '<li class=""><a data-page="' + (currentPage - i) + '">' + (currentPage - i) + '</a></li>';
            }
        }

        for(var i=currentPage;i<=pageCount;i++){
            if(i == (currentPage + 4)){
                break;
            }
            if(i == currentPage){
                page += '<li class="active"><a>' + i + '</a></li>';
            } else {
                page += '<li class=""><a  data-page="' + i + '">' + i + '</a></li>';
            }
        }

        if(pageCount != currentPage){

            if(currentPage < (pageCount - 4)){
                page += '<li class="disabled"><a> ... </a></li>';
            }

            if(currentPage < (pageCount - 3)){
                page += '<li><a data-page="' + pageCount + '">' + pageCount + '</a></li>';
            }
            page += '<li class="next"><a  data-page="' + (currentPage + 1) + '">下一页 → </a></li>';
        }
        oPageUl.html(page);

        var oPagesLi = $('#js-page li');
        oPagesLi.click(function () {
            if($(this).hasClass('disabled') || $(this).hasClass('active')){
                return;
            }
            var page = $(this).find('a').data('page');
            doPage(page, 10);
        });
    }, 'json');
}

$(function(){
    doPage(1, 10);
});

/**
 * var oUserBody = $('#js-user-body');
 */

var oUserBody = $('#js-user-body');


oUserBody.delegate('input', 'blur', function () {
    var oTr = $(this).closest('tr');
    oProfessionInput = oTr.find('input[name="profession"]');
    oDrillInput = oTr.find('input[name="drill"]');
    oScoreInput = oTr.find('input[name="score"]');
    oDurationInput = oTr.find('input[name="duration"]');

    var value = $(this).val();
    var origin = $(this).data('origin');
    var profession = oProfessionInput.val();
    profession = profession.replace(/，/g, ',').replace(/ /g, ''); //讲中文，转为因为, 将空格去掉
    if(value != origin){
        $.post('/admin/updateStore', {
            profession: profession,
            drill: oDrillInput.val(),
            score: oScoreInput.val(),
            duration: oDurationInput.val(),
            sid: $(this).data('sid')
        }, function(res){
            var d = dialog({
                content: '修改成功'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 1000);
        });
    }
})

oUserBody.delegate('.delbtn', 'click', function () {
    $.post('/admin/hideStore', {
        sid: $(this).data('sid')
    }, function(res){
        var d = dialog({
            content: '删除成功'
        });
        d.showModal();
        setTimeout(function () {
            d.close().remove();
            window.location.reload();
        }, 1000);
    });
});


$(function(){
    var tree;
    var newCount = 1;
    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
            + "' text='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_"+treeNode.tId);
        if (btn) btn.bind("click", function(){
            $.post('/admin/addCategory', {
                pid: treeNode.cid
            }, function (res) {
                if(treeNode.open){
                    tree.addNodes(treeNode, {cid: res._id, isParent: true, pId:treeNode.id, text:res.text});
                } else {
                    tree.expandNode(treeNode, true);
                }
            });
            return false;
        });
    };

    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_"+treeNode.tId).unbind().remove();
    };

    function zTreeOnAsyncSuccess(e, treeId, treeNode, msg){
        if(msg.length === 1 && msg[0].pid === '0'){ //表示是根节点
            //tree.expandNode(tree.getNodes()[0]);
        }
    }

    function zTreeOnRemove(e, treeId, treeNode){
        $.post('/admin/removeCategory', {
            'cid': treeNode.cid
        }, function (res) {

        });
    }

    function zTreeOnRename(e, treeId, treeNode){
        $.post('/admin/renameCategory', {
            cid: treeNode.cid,
            text: treeNode.text
        }, function (res) {

        });
    }

    //获取题目树形结构
    !function () {
        var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            edit: {
                enable: true,
                editNameSelectAll: true,
                showRemoveBtn: function (treeId, treeNode) {
                    if(!treeNode.pid){
                        return false;
                    }
                    return true;
                },
                showRenameBtn: true
            },
            async: {
                enable: true,
                type: 'POST',
                dataType : 'json',
                url:'/admin/category',
                autoParam:['cid']
            },
            data: {
                key: {
                    name: 'text'
                },
                simpleData: {
                    idKey: 'cid',
                    pIdKey: 'pid'
                }
            },
            callback: {
                onAsyncSuccess: zTreeOnAsyncSuccess,
                onRemove: zTreeOnRemove,
                onRename: zTreeOnRename
            }
        };
        tree = $.fn.zTree.init($("#questioncategory"), setting);
    }();

    var oQuestionForm = $('#question_form');
    oQuestionForm.submit(function () {
        var selectedNode = tree.getSelectedNodes();
        if(!selectedNode.length){
            var d = dialog({
                content: '请先在左边的树上选择一个节点'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 2000);
            return false;
        } else {
            oQuestionForm.find('input[name="cateType"]').val(selectedNode[0].cid);
        }
        var oTitle = oQuestionForm.find('input[name="text"]');
        if(!oTitle.val()){
            var d = dialog({
                content: '请填写题目集名称'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 2000);
            return false;
        }
        var oDrillScore= oQuestionForm.find('input[name="drill"]');
        if(!oDrillScore.val()){
            var d = dialog({
                content: '请填写练习积分'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 2000);
            return false;
        }
        var oBattleScore = oQuestionForm.find('input[name="score"]');
        if(!oBattleScore.val()){
            var d = dialog({
                content: '请填写挑战积分'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 2000);
            return false;
        }

        var oFile = oQuestionForm.find('input[type="file"]');
        if(!oFile.val()){
            var d = dialog({
                content: '请先选择要上传的题目集'
            });
            d.showModal();
            setTimeout(function () {
                d.close().remove();
            }, 2000);
            return false;
        }

        return true;
    });
});
